﻿using Nest;
using System;
using System.Linq.Expressions;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class NumRangeSpecification<T> : ISearchSpecification<ISearchRequest<T>> where T : class
    {
        private readonly int? _valueNumBegin;
        private readonly int? _valueNumEnd;
        private readonly Expression<Func<T, int>> _field;

        public NumRangeSpecification(int? valueNumBegin, int? valueNumEnd, Expression<Func<T, int>> field)
        {
            _valueNumBegin = valueNumBegin;
            _valueNumEnd = valueNumEnd;
            _field = field;
        }

        public ISearchRequest<T> IsSatisfiedBy()
        {
            return new SearchDescriptor<T>()
                .Query(q => q
                    .Range(m =>
                        {
                            var res = m.Field(_field);
                            if (_valueNumBegin != null)
                                res.GreaterThanOrEquals(
                                    _valueNumBegin.Value);
                            if (_valueNumEnd != null)
                                res.LessThanOrEquals(_valueNumEnd.Value);
                            return res;
                        }
                    )
                );
        }
    }
}